package com.changsideal.core;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.changsideal.entity.P;
import com.changsideal.tool.Constant;
import org.apache.commons.codec.binary.Base64;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;

/**
 * @ClassName S3Factory
 * @Description TODO
 * @Author Create by Chansideal.Haosc
 * @Date 2019/6/14 16:35
 * @Version 1.2
 **/
public final class S3Factory {

    private S3Factory() {
    }
    // this should be a namespace-enabled baseURL w/ wildcard DNS & SSL
    //public static final String PUBLIC_ENDPOINT = "https://" + S3_NAMESPACE + ".public.ecstestdrive.com";
//    public static final String PUBLIC_ENDPOINT = "https://<namespace>.public.ecstestdrive.com";

    public static AmazonS3 getS3ClientWithV4Signatures(P p) {
        return createBasicClientBuilder(p).build();
    }

    public static AmazonS3 getS3ClientWithV2Signatures(P p) {
        AmazonS3ClientBuilder builder = createBasicClientBuilder(p);
        builder.setClientConfiguration(new ClientConfiguration().withSignerOverride(Constant.S3_SIGNER_TYPE));
        return builder.build();

    }

    private static AmazonS3ClientBuilder createBasicClientBuilder(P p) {
        AmazonS3ClientBuilder builder = AmazonS3Client.builder();
        builder.setEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(p.getEndpoint(), p.getRegion().getName()));
        builder.setCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(p.getAccess_key_id(), p.getSecret_key())));
        builder.setPathStyleAccessEnabled(true);
        return builder;
    }

    public static void main(String[] args) {
        try {
            KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(Constant.SECRET_TYPE);
            keyGenerator.initialize(1024, new SecureRandom());
            KeyPair myKeyPair = keyGenerator.generateKeyPair();

            // Serialize.
            byte[] pubKeyBytes = myKeyPair.getPublic().getEncoded();
            byte[] privKeyBytes = myKeyPair.getPrivate().getEncoded();

            String pubKeyStr = new String(Base64.encodeBase64(pubKeyBytes, false), Constant.CHARSET_TYPE_NAME);
            String privKeyStr = new String(Base64.encodeBase64(privKeyBytes, false), Constant.CHARSET_TYPE_NAME);

            System.out.println("Public Key: " + pubKeyStr);
            System.out.println("Private Key: " + privKeyStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
